package edu.stu.mall.fragment.home


import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import edu.mall.base.BaseFragment
import edu.mall.base.SingleLiveEvent
import edu.mall.base.view.NoScrollLayoutManager
import edu.stu.mall.BR
import edu.stu.mall.R
import edu.stu.mall.activity.recommended.ProductDetailActivity
import edu.stu.mall.adapter.HomeItemClassificationAdapter
import edu.stu.mall.adapter.RecommendedProductAdapter
import edu.stu.mall.databinding.FragmentHomeBinding
import edu.stu.mall.repository.data.ItemModel
import edu.stu.mall.repository.data.RecommendedProductDataItem

class FragHome : BaseFragment<FragmentHomeBinding, FragHomeViewModel>() {

    private val recommendedProductAdapter = RecommendedProductAdapter()
    private val homeItemClassificationAdapter = HomeItemClassificationAdapter()

    override fun getLayoutId(): Int {
        return R.layout.fragment_home
    }

    override fun getViewModelId(): Int {
        return BR.homeVm
    }

    override fun initViewData() {
        initListView()
        initObserverData()
    }

    private fun initObserverData() {
        viewModel?.recommendedList?.observe(viewLifecycleOwner) { list ->
            recommendedProductAdapter.setData(list)
        }

        getBanner()
        initClass()
    }

    private fun initClass() {
        // 创建商品分类列表
        val items = listOf(
            ItemModel(R.drawable.ic_class__1_, "眼睛"),
            ItemModel(R.drawable.ic_class__2_, "包包"),
            ItemModel(R.drawable.ic_class__3_, "耳机"),
            ItemModel(R.drawable.ic_class__4_, "鞋子"),
            ItemModel(R.drawable.ic_class__5_, "化妆品"),
            ItemModel(R.drawable.ic_class__6_, "母婴"),
            ItemModel(R.drawable.ic_class__7_, "裙子"),
            ItemModel(R.drawable.ic_class__8_, "手机"),
            ItemModel(R.drawable.ic_class__9_, "书籍"),
            ItemModel(R.drawable.ic_class__10_, "游戏"),
            ItemModel(R.drawable.ic_class__11_, "游戏"),
            ItemModel(R.drawable.ic_class__12_, "游戏"),
            ItemModel(R.drawable.ic_class__13_, "游戏"),
            ItemModel(R.drawable.ic_class__14_, "泳圈"),
            ItemModel(R.drawable.ic_class__15_, "冰淇淋"),
            ItemModel(R.drawable.ic_class__16_, "甜甜圈"),
            ItemModel(R.drawable.ic_class__17_, "香水"),
            ItemModel(R.drawable.ic_class__18_, "网球"),
            ItemModel(R.drawable.ic_class__19_, "桌椅"),
            ItemModel(R.drawable.ic_class__5_, "化妆品"),
            ItemModel(R.drawable.ic_class__20_, "汽车"),
            ItemModel(R.drawable.ic_class__21_, "相机")
        )

        // 创建一个网格布局管理器，每行2个item，水平滚动
        val layoutManager = GridLayoutManager(context, 2, GridLayoutManager.HORIZONTAL, false)
        binding?.rlvClassification?.layoutManager = layoutManager
        binding?.rlvClassification?.adapter = homeItemClassificationAdapter

        // 设置 ViewModel 的初始数据
        viewModel?.setInitialData(items)
        viewModel?.classList?.observe(viewLifecycleOwner) { list ->
            // 更新适配器数据
            homeItemClassificationAdapter.setData(list)
        }

        // 添加滚动监听器
        binding?.rlvClassification?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                // 计算并更新滚动条的位置
                val totalScrollRange = recyclerView.computeHorizontalScrollRange()
                val scrollOffset = recyclerView.computeHorizontalScrollOffset()
                val scrollExtent = recyclerView.computeHorizontalScrollExtent()
                val scrollPercent = if (totalScrollRange - scrollExtent > 0) {
                    scrollOffset.toFloat() / (totalScrollRange - scrollExtent).toFloat()
                } else {
                    0f
                }
                if (binding!!.scrollBar1.getInitialState()) {
                    binding!!.scrollBar1.animateTo(scrollPercent)
                }
            }
        })
    }



    private fun getBanner() {
        viewModel?.bannerData?.observe(viewLifecycleOwner) { bannerData ->
            val advertiseList = bannerData?.advertiseList
            val bannerList = advertiseList?.map { it.pic.toString() }?.toMutableList()

            binding?.banner?.apply {
                indicator = CircleIndicator(context)
                setLoopTime(4000)
                addBannerLifecycleObserver(viewLifecycleOwner)
                setIndicatorWidth(15, 15)
                setAdapter(object : BannerImageAdapter<String>(bannerList) {
                    override fun onBindView(
                        holder: BannerImageHolder,
                        data: String,
                        position: Int,
                        size: Int
                    ) {
                        context?.let {
                            Glide.with(it)
                                .load(data)
                                .into(holder.imageView)
                        }
                    }
                })
            }
        }
    }


    private fun initListView() {

        // 使用context?.let确保只有在context非空时，才会创建NoScrollLayoutManager的实例。
        var recommendedProductLayoutManager = context?.let { NoScrollLayoutManager(it, 2) }
        binding?.rlvRecommended?.layoutManager = recommendedProductLayoutManager
        binding?.rlvRecommended?.adapter = recommendedProductAdapter

        // 5.注册点击事件监听
        recommendedProductAdapter.setItemClickListener(object :
            RecommendedProductAdapter.RecommendItemClickListener {
            override fun onItemClick(item: RecommendedProductDataItem) {


                val intent = Intent(context, ProductDetailActivity::class.java)
                val bundle = Bundle()
                bundle.putString("id", item.id.toString()) // 这里可以是任何String值
                intent.putExtras(bundle)
                startActivity(intent)
            }
        })


    }
}